package com.itheima.service.impl;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import com.itheima.dao.OrderDao;
import com.itheima.model.OrderInfo;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author：shenkunlin
 * @date： 2021/7/5 12:01
 * @Description：
 ***/
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RestTemplate restTemplate;

    //1）注入NacosServiceDiscovery
    @Autowired
    private NacosServiceDiscovery nacosServiceDiscovery;

    /***
     * 添加订单
     * @param orderInfo
     * @return
     */
    @Override
    public int save(OrderInfo orderInfo) throws NacosException {
        //执行远程请求
        //2）从注册中心中获取服务列表
        List<ServiceInstance> serviceInstances = nacosServiceDiscovery.getInstances("item");//根据服务的名字获取服务列表

        //3）从服务列表中随机选择一个服务（测试：选第1个）
        ServiceInstance serviceInstance = serviceInstances.get(0);

        //4）将请求路径中的IP和端口动态切换
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/item/"+orderInfo.getItemId()+"/"+orderInfo.getCount();
        int price = restTemplate.getForObject(url,Integer.class);
        //设置总金额
        orderInfo.setPrice(orderInfo.getCount()*price);
        //下单
        return orderDao.save(orderInfo);
    }



    /***
     * 添加订单
     * @param orderInfo
     * @return
     */
    public int saveRestTemplate(OrderInfo orderInfo) {
        String url = "http://localhost:18081/item/"+orderInfo.getItemId()+"/"+orderInfo.getCount();
        //执行远程请求
        int price = restTemplate.getForObject(url,Integer.class);//  1）远程访问的地址  2）远程方法执行返回结果需要转换的类型
        //设置总金额
        orderInfo.setPrice(orderInfo.getCount()*price);
        //下单
        return orderDao.save(orderInfo);
    }

    /**
     * 根据ID查询订单信息
     * @param id
     * @return
     */
    @Override
    public OrderInfo one(Integer id) {
        return orderDao.one(id);
    }
}